<?php
namespace backend\controllers;

use backend\models\PackageInitiation;
use yii;
use yii\filters\AccessControl;

use backend\models\MigrationPackageTransfer;
use backend\models\MigrationProject;
use backend\models\ProjectPreEvaluationMortgage;
use backend\models\ProjectPreEvaluationSealClone;
use backend\models\UserClone;
use backend\models\PackageEase;
use backend\models\MigrationPackageTarget;
use backend\models\MigrationPackage;
use backend\models\PackageEaseTransfer;
use backend\models\MigrationPackageTransferTarget;
use backend\models\ProjectEase;
use backend\models\MigrationProjectTarget;

class PackageMigrationController extends yii\web\Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionPackage()
    {
        $migrationModel = new MigrationPackage();
        $arr_id = Yii::$app->request->post("id");
        if ($arr_id == null) {
            Yii::$app->session->setFlash('danger', '请先选择要迁移的数据。');
            return $this->redirect(['package-ease/index']);
        }
        $str_id = implode(',', $arr_id);
        $map = "`id` in ($str_id)";
        $arr_package_ease = PackageEase::find()->where($map)->all();
        $packageModel = new MigrationPackageTarget();

        if (is_array($arr_package_ease) && count($arr_package_ease) > 0) {
            foreach ($arr_package_ease as $count => $package) {
                if ($package->is_migrated == 1) {
                    Yii::$app->session->addFlash('warning', $package->title . '已经迁移过了。');
                    continue;
                }
                $clonePackageModel = clone $packageModel;
                $clonePackageModel->attributes = $package->getAttributes();
                $clonePackageModel->is_finished = 1;
                $clonePackageModel->source = 1;
                //用户表已统一，无需再查询
//                $owner = UserClone::getNewId($package->owner);//获取新的用户id
//                if ($owner) {
//                    $clonePackageModel->owner = $owner;
//                } else {
//                    Yii::$app->session->addFlash('danger', $package->title . "无对应用户$package->owner,无法迁移。");
//                    continue;
//                }
                if ($clonePackageModel->save()) {
                    $cloneMigrationModel = clone $migrationModel;
                    $cloneMigrationModel->original_package_id = $package->id;
                    $cloneMigrationModel->new_package_id = $clonePackageModel->id;

                    @$cloneMigrationModel->save();

                    //添加资产包负责人信息
                    $packageIniModel = new PackageInitiation();
                    $packageIniModel->package_id=$clonePackageModel->id;
                    $packageIniModel->leader = Yii::$app->user->id;
                    $packageIniModel->save();
                    
                    //迁移转让信息
                    $this->actionPackageTransfer($package->id, $cloneMigrationModel->new_package_id);
                    //迁移项目信息
                    $this->actionProject($package->id, $cloneMigrationModel->new_package_id);
                    $package->is_migrated = 1;
                    @$package->save();
                    Yii::$app->session->addFlash('success', $package->id . $package->title . ' 迁移成功。');
                } else {
                    Yii::$app->session->addFlash('danger', $package->id . $package->title . " 迁移错误：" . serialize($clonePackageModel->getFirstErrors()));
                    Yii::info('Package' . $package->id . $package->title . " migrate error:" . serialize($clonePackageModel->getFirstErrors()));
                }
            }
        } else {
            Yii::$app->session->addFlash('warning', "没有可迁移的资产包。");
        }
        return $this->redirect(Yii::$app->request->referrer);
    }

    public function actionPackageTransfer($package_id, $new_package_id)
    {
        $migrationModel = new MigrationPackageTransfer();
        $arr_transfer = PackageEaseTransfer::find()->where(['package_id' => $package_id])->all();
        $transferModel = new MigrationPackageTransferTarget();
        if (is_array($arr_transfer) && count($arr_transfer) > 0) {
            foreach ($arr_transfer as $key => $item) {
                $cloneTransferModel = clone $transferModel;
                $cloneTransferModel->attributes = $item->getAttributes();
                $cloneTransferModel->package_id = $new_package_id;//取新的package_id
                if ($cloneTransferModel->save()) {
                    $cloneMigrationModel = clone $migrationModel;
                    $cloneMigrationModel->original_transfer_id = $item->id;
                    $cloneMigrationModel->new_transfer_id = $cloneTransferModel->id;
                    @$cloneMigrationModel->save();
//                    Yii::$app->session->addFlash('success', "转让信息 " . $item->id . ' 迁移成功。');
                } else {
                    Yii::$app->session->addFlash('success', "转让信息 " . $item->id . ' 迁移错误：' . serialize($cloneTransferModel->getFirstErrors()));
                    Yii::info("Package_transfer " . $item->id . ' migrate error' . serialize($cloneTransferModel->getFirstErrors()));
                }
            }
        } else {
//            Yii::$app->session->addFlash('info', $package_id . "无转让信息。");
        }
    }

    public function actionProject($package_id, $new_package_id)
    {
        $migrationModel = new MigrationProject();

        $arr_project = ProjectEase::find()->where(['package_id' => $package_id])->all();
        $projectModel = new MigrationProjectTarget();

        if (is_array($arr_project) && count($arr_project) > 0) {
            //1存续2吊销3注销4破产
            $arr_management_status = [1 => 4, 2 => 1, 3 => 2, 4 => 3];

            foreach ($arr_project as $key => $item) {
                $cloneProjectModel = clone $projectModel;
                $original_project_attributes = $item->getAttributes();
                $project_attributes = array_slice($original_project_attributes, 1, 12);

                $cloneProjectModel->attributes = $project_attributes;
                $cloneProjectModel->guarantor = $item->stakeholders;
                $cloneProjectModel->guarantor_status = $item->stakeholders_status;
                $cloneProjectModel->mortgage_details = $item->mortgage_detail;
                $cloneProjectModel->package_id = $new_package_id;
                $cloneProjectModel->type = '';
                $cloneProjectModel->type2 = $item->category;
                $cloneProjectModel->management_status = $arr_management_status[$item->management_status];

                if ($cloneProjectModel->save()) {
                    $cloneMigrationModel = clone $migrationModel;
                    $cloneMigrationModel->original_project_id = $item->id;
                    $cloneMigrationModel->new_project_id = $cloneProjectModel->id;
                    @$cloneMigrationModel->save();
//                    Yii::$app->session->addFlash('success', "项目 " . $item->title . $item->id . '迁移成功。');
                } else {
                    Yii::$app->session->addFlash('danger', "项目 " . $item->title . $item->id . ' 迁移错误' . serialize($cloneProjectModel->getFirstErrors()));
                    Yii::info("Project " . $item->id . ' migrate error' . serialize($cloneProjectModel->getFirstErrors()));
                }

            }
        } else {
//            Yii::$app->session->addFlash('info', '此资产包没有可迁移的项目');
        }
    }
}